package com.ttbj.websocket;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.ttbj.api.dto.SalesmanDto;
import com.ttbj.constant.Const;

//该对象作为页面连接websocket服务的拦截器
//beforeHandshake，在调用handler前处理方法。
public class PushSalMessageIterator implements HandshakeInterceptor{
	
	private Logger LOGGER = LoggerFactory.getLogger(PushSalMessageIterator.class);
	
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		LOGGER.info("beforeHandshake...");
		if (request instanceof ServletServerHttpRequest) {
			ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
			//getSession(true)：若存在会话则返回该会话，否则新建一个会话
			//getSession(false)：若存在会话则返回该会话，否则返回NULL
			HttpSession session = serverHttpRequest.getServletRequest().getSession(false);
			if (null != session) {
				SalesmanDto salesmanDto = (SalesmanDto) session.getAttribute(Const.TTBJ_USER_SESSION_KEY);
				String salesmanName = salesmanDto.getSalesmanName();	//获取登录名
				attributes.put("WEBSOCKET_USERNAME", salesmanName);
				return true;
			}else {
				return false;
			}
		}else {
			return false;
		}
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {
	}

}
